<template>
  <div id="editorChange">
    <el-collapse v-model="activeNames1">
      <el-collapse-item title="内容" name="1">
        <div id="wangeditor">
          <div ref="editorElem"></div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-collapse v-model="activeNames2">
      <el-collapse-item title="内容样式" name="2">
        <ul class="content-list">
          <li>
            <span>上间距：</span>
            <div>
              <edgeSetting v-model="styles.marginTop" unit="px" :max="50" :init="0"></edgeSetting>
            </div>
          </li>
          <li>
            <span>下间距：</span>
            <div>
              <edgeSetting v-model="styles.marginBottom" unit="px" :max="50" :init="0"></edgeSetting>
            </div>
          </li>
          <li>
            <span>左右间距：</span>
            <div>
              <edgeSetting v-model="styles.marginLR" unit="px" :max="50" :init="0"></edgeSetting>
            </div>
          </li>
          <li>
            <span>圆角：</span>
            <div>
              <edgeSetting v-model="styles.circle" unit="px" :max="15" :init="10"></edgeSetting>
            </div>
          </li>
        </ul>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
import { mapState } from "vuex";
import E from "wangeditor";
import edgeSetting from "../../comm/edgeSetting";

export default {
  name: "editorChange",
  data() {
    return {
      editor: null,
      editorContent: "",
      activeNames1: "1",
      activeNames2: "2",
    };
  },
  mounted() {
    this.initEditor();
  },
  methods: {
     // 模拟上传方法-开发时候用（直接返回测试URL）
    upload1(formData) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ 
            imgUrl: 'https://dummyimage.com/600x400/000/fff.png&text=Mock+Image' 
          });
        }, 500);
      });
    },
     // 真实上传方法（需要后端支持）
    async upload2(formData) {
      try {
        const res = await this.$axios.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        return { imgUrl: res.data.url };
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('图片上传失败,需要后端上传接口');
        throw error; // 抛出错误让编辑器处理
      }
    },
     // 阿里云OSS上传示例
    async upload(formData) {
      const bucket = 'do-dora'//测试
      // const bucket = 'do-dora-formal'//正式
      const OSS = require('ali-oss');
      const client = new OSS({
        region: 'oss-cn-chengdu',
        endpoint: 'oss-cn-chengdu.aliyuncs.com', // 填写Bucket所在地域
        accessKeyId: 'LTAI5tMcw8NE6zrUD1kJ1upi',
        accessKeySecret: 'jSrijmWOUKFccu8giHxXgvDkGUULgP',
        bucket: bucket
      });

      try {
        const file = formData.get('file');
        const result = await client.put(`uploads/${Date.now()}_${file.name}`, file);
        return { imgUrl: result.url };
      } catch (error) {
        console.error('OSS上传失败:', error);
        throw error;
      }
    },
    initEditor() {
      this.editor = new E(this.$refs.editorElem);
      
      // 配置编辑器
      this.editor.config.onchange = (html) => {
        this.editorContent = html;
        this.styles.html = html;
      };
      
      this.editor.config.menus = [
        'head', 'bold', 'fontSize', 'italic', 'underline',
        'strikeThrough', 'foreColor', 'backColor', 'link',
        'list', 'justify', 'quote', 'emoticon', 'image',
        'undo', 'redo'
      ];
      
      // 图片上传配置
      this.editor.config.uploadImgMaxSize = 3 * 1024 * 1024;
      this.editor.config.uploadImgMaxLength = 5;
      this.editor.config.customUploadImg = async (files, insert) => {
        try {
          const formData = new FormData();
          formData.append("file", files[0]);
          const data = await this.upload(formData);
          insert(data.imgUrl);
        } catch (error) {
          console.error('上传失败:', error);
        }
      };
      
      this.editor.create();
      
      // 如果有初始内容
      if (this.styles.html) {
        this.editor.txt.html(this.styles.html);
      }
    }
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
  },
  components: { edgeSetting },
  computed: {
    ...mapState(["list", "currentId", "currentName"]),
    styles() {
      return this.list[this.currentId].styles;
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../../assets/css/base.less");
#wangeditor {
  border: 1px solid #ddd;
  
  /* 工具栏样式 */
  .w-e-toolbar {
    flex-wrap: wrap;
    background-color: #f1f1f1;
    border-bottom: 1px solid #ddd;
  }
  
  /* 编辑区域样式 */
  .w-e-text-container {
    height: 500px !important;
  }
}
</style>